<template>
  <div class="home">
    <van-nav-bar title="极客头条" fixed @click-right="$router.push('/search')">
      <template #right>
        <van-icon name="search" size="20px" />
      </template>
    </van-nav-bar>

    <van-tabs
      v-model="channelId"
      animated
      swipeable
      sticky
      offset-top="1.2267rem"
      ellipsis
      @change="changneChangeFn"
    >
      <van-tab
        :title="item.name"
        :name="item.id"
        v-for="item in userChannelList"
        :key="item.id"
      >
        <ArticleList :cid="item.id"></ArticleList>
      </van-tab>
    </van-tabs>
    <!-- 编辑频道图标 -->
    <van-icon
      name="plus"
      size="0.37rem"
      class="moreChannels"
      @click="show = true"
    />
    <!-- 编辑频道弹出层 -->
    <van-popup
      v-model="show"
      class="edit_wrap"
      @closed="$refs.channelEdit.isEdit = false"
    >
      <ChannelEdit
        @close="show = false"
        @addChannel="addChannel"
        @removeChannel="removeChannel"
        @changeChannel="changeChannel"
        :userChannelList="userChannelList"
        :unCheckChannelList="unCheckChannelList"
        ref="channelEdit"
      ></ChannelEdit>
    </van-popup>
  </div>
</template>

<script>
import { getUserChannels, getChannels, updateUserChannels } from "@/api";
import ArticleList from "./components/ArticleList.vue";
import ChannelEdit from "./ChannelEdit.vue";
export default {
  name: "Home",
  components: {
    ArticleList,
    ChannelEdit,
  },
  data() {
    return {
      channelId: 0,
      userChannelList: [],
      // 编辑频道弹出层显示
      show: false,
      allChannelList: [], // 所有频道
      channelScrollTObj: {}, // 保存每个频道的滚动位置
      // 值样子构想: {推荐频道ID: 滚动距离, html频道ID: 自己滚动距离}
    };
  },
  created() {
    console.log('创建');
    this.getUserChannels();
    this.getChannels();
  },

  methods: {
    // 获取用户频道列表
    async getUserChannels() {
      const res = await getUserChannels();
      this.userChannelList = res.data.channels;
    },
    // 获取所有频道列表
    async getChannels() {
      const res = await getChannels();
      this.allChannelList = res.data.channels;
    },
    // 更新用户频道
    async updateUserChannels() {
      // 先拷贝一份数组(前端页面用channelList, 后端用拷贝出的数组)
      // 数组第一层, 对象里key+value是第二层
      const newArr = this.userChannelList.filter((item) => item.id !== 0);
      const theNewArr = newArr.map((obj, index) => {
        const newObj = { ...obj };
        delete newObj.name;
        newObj.seq = index;
        return newObj;
      });

      const res = await updateUserChannels(theNewArr);
    },
    // 添加频道
    addChannel(obj) {
      this.userChannelList.push(obj);

      this.updateUserChannels();
    },
    // 删除频道
    removeChannel(obj) {
      const ind = this.userChannelList.findIndex((item) => item.id === obj.id);
      this.userChannelList.splice(ind, 1);
      this.updateUserChannels();
    },
    changeChannel(obj) {
      // 传过来的频道ID, 影响tabs默认v-model的选择
      this.channelId = obj.id;
    },
    // 监听网页滚动事件
    scrollFn() {
      // 谷歌浏览器内核, 和安卓手机内置浏览器的内核不是同一个
      // 获取scrollTop方式不同
      // 谷歌浏览器用的html的scrollTop
      // 有的浏览器用的body的scrollTop
      this.$route.meta.scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 同时保存当前频道的滚动距离
      this.channelScrollTObj[this.channelId] =
        document.documentElement.scrollTop || document.body.scrollTop;
    },
    // tabs页切换事件
    changneChangeFn(){
      // 等 DOM 更新完毕之后，根据记录的"滚动条位置"，调用 window.scrollTo() 方法进行滚动
      this.$nextTick(()=> document.documentElement.scrollTop = this.channelScrollTObj[this.channelId] || 0)
      
    }
  },

  // 路由离开 - 触发(保存滚动位置)
  // beforeRouteLeave(to, from, next) {
  //   console.log("离开");
  //   from.meta.scrollTop = window.scrollY;
  //   next();
  // },
  activated() {
    console.log('激活');
    // 监听网页滚动事件 保存滚动距离
    window.addEventListener("scroll", this.scrollFn);
    document.documentElement.scrollTop = this.$route.meta.scrollTop;
  },
  deactivated() {
    console.log('缓存');
    // 移除滚动事件
    window.removeEventListener("scroll", this.scrollFn);
  },

  computed: {
    unCheckChannelList() {
      // 把所有频道数组挨个对象取出, 去用户已选频道数组里查找, 如果找不到, 则让filter方法收集到一个新数组里
      const newArr = this.allChannelList.filter((allItem) => {
        const index = this.userChannelList.findIndex((userItem) => {
          return allItem.id === userItem.id;
        });
        // 如果找到了
        if (index > -1) {
          return false;
        } else {
          return true;
        }
      });
      return newArr;
    },
  },
};
</script>

<style lang="less" scoped>
.home {
  padding-top: 46px;
  padding-bottom: 50px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 60px;
  right: 10px;
  z-index: 999;
}

.edit_wrap {
  width: 100vw;
  height: 100vh;
}
</style>
